package com.tarena.lbs.basic.web.filters;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
public class AuthenticationFilter implements Filter {

    private JwtEncoder<UserPrinciple> jwtEncoder;
    //过滤的核心逻辑 三个参数

    /**
     * @param servletRequest servlet请求 一定是http请求
     * @param servletResponse servlet响应 一定是http响应
     * @param filterChain 过滤链
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Thread.currentThread();
        System.out.println("进过滤器1");
        //1.请求中携带了头 servletRequest转化成HttpServletRequest
        UserPrinciple userPrinciple=null;
        if (servletRequest instanceof HttpServletRequest){
            HttpServletRequest request=(HttpServletRequest) servletRequest;
            String jwt=request.getHeader("Authorization");
            //2. 判断存在
            if (StringUtils.isNotBlank(jwt)){
                //3.解析jwt成为UserPrinciple
                try{
                    userPrinciple=jwtEncoder.getLoginFromToken(jwt,UserPrinciple.class);
                }catch (BusinessException e){
                    log.error("解析失败",e);
                }
            }
        }
        //4.向后传递参数
        ThreadLocalUtils.set(userPrinciple);
        filterChain.doFilter(servletRequest,servletResponse);
        //出过滤器 请求即将结束 清空数据
        ThreadLocalUtils.clear();
        System.out.println("出过滤器1");
    }
}
